from typing import List

from fastapi import APIRouter, Depends
import json
from sqlalchemy import select, desc, func, distinct
from sqlalchemy.ext.asyncio import AsyncSession
from apis.deps import get_db
from schemas import MailSenderCreate, MailSenderUpdate, MailSenderOut as MailSender, Result, ResultPlus
from crud import mail_sender
from utils import resp_200, IdNotExist
from models import MailSender as MailSenderModel
from utils.sendReportEmail import send_report_email

router = APIRouter()


@router.post("/createMailSender", summary="新增发件人邮箱")
async def create_mail_sender(mail_sender_in: MailSenderCreate, db: AsyncSession = Depends(get_db)):
    await mail_sender.create(db=db, obj_in=mail_sender_in)
    return resp_200(msg=f"成功添加收件人邮箱.")


@router.get("/getMailSender", summary='查询发件人邮箱')
async def get_project(project_id: int = 0, db: AsyncSession = Depends(get_db)):
    get_mail_sender_arr_sql = await db.execute(
        select(MailSenderModel).order_by(desc(MailSenderModel.id)).where(MailSenderModel.project_id == project_id))
    get_mail_sender_arr = get_mail_sender_arr_sql.scalars().first()
    return resp_200(msg=f"查询成功", data=get_mail_sender_arr)


@router.put("/updateMailSender", summary="更新发件人邮箱")
async def update_mail_sender(id: int, mail_sender_in: MailSenderUpdate, db: AsyncSession = Depends(get_db)):
    await mail_sender.update(db=db, id=id, obj_in=mail_sender_in)
    return resp_200(msg=f"修改了id为{id}的邮件.")


@router.post("/testMailSender", summary="发件人测试")
async def test_mail_sender(name: str, password: str, ):
    if send_report_email(name, password, [name], '发件人测试', '发件人测试'):
        return resp_200(msg=f"发件人测试成功")
    else:
        return {"code": 201, "msg": "验证失败"}
